﻿using AuthCenter.API.Application.Command.AccountRole;
using AuthCenter.API.DTOs;
using AuthCenter.Domain.Account;
using AuthCenter.ErrorCode;
using AuthCenter.Intertructrue.Interface;
using AutoMapper;
using MediatR;

namespace AuthCenter.API.Application.Handler.AccountRole
{
    public class FindRoleUserHandler : IRequestHandler<FindRoleUserCommand, APIResult<List<AccountRoleDTO>>>
    {
        private readonly IBaseRepository<AccountModel> accountRepo;
        private readonly IBaseRepository<AccountRoleModel> accountroleRepo;
        private readonly IBaseRepository<RoleModel> roleRepo;
        private readonly IMapper mapper;

        public FindRoleUserHandler(IBaseRepository<AccountModel> accountRepo,
                                   IBaseRepository<AccountRoleModel> accountroleRepo,
                                   IBaseRepository<RoleModel> roleRepo,
                                   IMapper mapper)
        {
            this.accountRepo = accountRepo;
            this.accountroleRepo = accountroleRepo;
            this.roleRepo = roleRepo;
            this.mapper = mapper;
        }
        public Task<APIResult<List<AccountRoleDTO>>> Handle(FindRoleUserCommand request, CancellationToken cancellationToken)
        {
            APIResult<List<AccountRoleDTO>> result = new APIResult<List<AccountRoleDTO>>();
            var list = accountroleRepo.GetAll().Where(x => x.RoleId == request.RoleId&&!x.IsDel).ToList();
            var accountroleDTO = mapper.Map<List<AccountRoleDTO>>(list);

            foreach (var item in accountroleDTO)
            {
                item.AccountRoleId = accountroleRepo.GetAll().FirstOrDefault(x => x.RoleId == request.RoleId).Id;
                item.Name = accountRepo.GetAll().FirstOrDefault(x => x.Id == item.AccountId && !x.IsDel).Name;
                item.Department = accountRepo.GetAll().FirstOrDefault(x=>x.Id==item.AccountId && !x.IsDel).Department;
            }
            result.Message = "显示分配人员成功";
            result.Code = APIEnum.Ok;
            result.Data = accountroleDTO;
            return Task.FromResult(result);
        }
    }
}
